#include "MCDrawArcCommand.h"
#include <iostream>
#include <MCMathUtils.h>

MCDrawArcCommand::MCDrawArcCommand(MCCommandManager *owner) :
    MCCommand(owner),
    _arcVisual(new MCArcVisual(presenter, MCArc2D())),
    _tempCircleVisual(new MCCircleVisual(presenter, MCCircle2D())),
    _currentStage(MCDrawArcStage::Arc_SetCenter),
    _parametricWindow(nullptr)
{
    presenter->addVisualItem(_arcVisual);
    presenter->addVisualItem(_tempCircleVisual);
}

MCDrawArcCommand::~MCDrawArcCommand()
{
    if (_parametricWindow != nullptr)
    {
        delete _parametricWindow;
    }
}

void MCDrawArcCommand::onMouseDown(IMouseArgs &args)
{
    if (args.isLeftMousePressed())
    {
        if (_currentStage == MCDrawArcStage::Arc_SetCenter)
        {
            _settedCenter = args.globalPos();
            _arcVisual->update(_settedCenter, 0, 0, 0);
            _tempCircleVisual->update(_settedCenter, 0);
            _currentStage = MCDrawArcStage::Arc_SetRadius;
        }
        else if (_currentStage == MCDrawArcStage::Arc_SetRadius)
        {
            _settedRadius = _settedCenter.distanceTo(args.globalPos());
            MCVector2 curVec(args.globalPos() - _settedCenter);
            _settedStartAngle = MCMathUtils::normalizeAngle(MCVector2(1, 0).clockwiseAngle(curVec));
            _arcVisual->update(_settedCenter, _settedRadius, _settedStartAngle, _settedStartAngle);
            _tempCircleVisual->update(_settedCenter, 0);

            _currentStage = MCDrawArcStage::Arc_SetEndAngle;
        }
        else if (_currentStage == MCDrawArcStage::Arc_SetEndAngle)
        {
            MCVector2 curVec2(args.globalPos() - _settedCenter);
            _settedEndAngle = MCMathUtils::normalizeAngle(MCVector2(1, 0).clockwiseAngle(curVec2));
            presenter->removeVisualItem(_tempCircleVisual);
            _currentStage = MCDrawArcStage::Arc_ParametricWindow;

            _parametricWindow = new MCArcParametricWindow(this, _arcVisual);
            _parametricWindow->show();
        }
    }
    else if (args.isRightMousePressed())
    {
        terminate();
    }
}

void MCDrawArcCommand::onMouseUp(IMouseArgs &args)
{
}

void MCDrawArcCommand::onMouseMove(IMouseArgs &args)
{
    if (_currentStage == MCDrawArcStage::Arc_SetRadius)
    {
        _settedRadius = args.globalPos().distanceTo(_settedCenter);
        _tempCircleVisual->update(_settedCenter, _settedRadius);
    }

    else if (_currentStage == MCDrawArcStage::Arc_SetEndAngle)
    {
        MCVector2 curVec2(args.globalPos() - _settedCenter);
        _settedEndAngle = MCMathUtils::normalizeAngle(MCVector2(1, 0).clockwiseAngle(curVec2));
        _arcVisual->update(_settedCenter, _settedRadius, _settedStartAngle, _settedEndAngle);
    }
}

void MCDrawArcCommand::terminate()
{
    presenter->removeVisualItem(_arcVisual);
    presenter->removeVisualItem(_tempCircleVisual);
}
